package com.glc.hms.holder;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.IteratorUtils;

import java.io.Serializable;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Santa
 * @date 2019/12/11
 */
@Slf4j
public class ShiroSessionHolder {
    private static Cache<String,Map<Long, Deque<Serializable>>> cache;


    public synchronized static Cache<String,Map<Long, Deque<Serializable>>> getCache(Integer initNum){
        if(cache == null){
            cache = CacheUtil.newFIFOCache(initNum);
            Map<Long, Deque<Serializable>> map = Maps.newHashMap();
            cache.put("Session",map);
        }
        return cache;
    }
    public synchronized static Map<Long, Deque<Serializable>> getSessionCache(){
        Map<Long, Deque<Serializable>> sessions = cache.get("Session");
        if(sessions == null || sessions.size()==0){
            log.info("No session in cache");
            return null;
        }else {
            return sessions;
        }
    }

    public synchronized static List<Serializable> getSessionCacheList(){
        List<Serializable> sessionIds = Lists.newArrayList();
        Map<Long, Deque<Serializable>> sessions = ShiroSessionHolder.getSessionCache();
        for (Long userId : sessions.keySet()) {
            Deque<Serializable> deque = sessions.get(userId);
            if(deque.size()>0){
                Iterator<Serializable> iterator = deque.iterator();
                sessionIds.addAll(IteratorUtils.toList(iterator));
            }
        }
        return sessionIds;
    }
}























